package org.balabala.video.utils;

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @author Jaz
 * @since 2021-09-16 10:01
 * --QQ: 2247255931
 * --Email: Jiaauo@nwafu.edu.cn--
 */
public class FetchFrame {

    public static ByteArrayOutputStream fetchFrame(MultipartFile videoFile) throws Exception {
        File tempFile = new File(System.currentTimeMillis()+"temp");
        OutputStream fileOutPutStream = new FileOutputStream(tempFile);
        fileOutPutStream.write(videoFile.getBytes());
        fileOutPutStream.flush();
        fileOutPutStream.close();
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(tempFile);
        ff.start();
        int length = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < length) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
            if ((i > 5) && (f.image != null)) {
                break;
            }
            i++;
        }
        opencv_core.IplImage img = f.image;
        int owidth = img.width();
        int oheight = img.height();
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        image.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
                0, 0, null);

        ByteArrayOutputStream frameStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", frameStream);
        ff.stop();
        tempFile.delete();
        return frameStream;
    }

}
